import {
  View,
  Text,
  SafeAreaView,
  StyleSheet,
  Dimensions,
  ScrollView,
  Image,
  Pressable,
  Alert,
} from "react-native";
import React, { useEffect, useState } from "react";

import Icon from "react-native-vector-icons/Ionicons";

import { getArticleListApi } from "../../../api/article";
import { Article, PageResult } from "../../../types/api";
import { friendlyTimeAgo } from "../../../utils/time";
import { BASE_URL } from "../../../config";

const width = Dimensions.get("window").width;
const height = Dimensions.get("window").height;

export default function Home(props: any) {
  const navigation = props.navigation;

  const [articleList, setArticleList] = useState<Article[]>();

  useEffect(() => {
    getArticleList();
  }, []);

  async function getArticleList() {
    const res = await getArticleListApi<PageResult<Article[]>>({
      page: 1,
      limit: 5,
    });

    if (res.code == 200) {
      console.log(res.data.list);
      setArticleList(res.data.list);
    } else {
      Alert.alert("获取文章列表失败");
    }
  }

  function gotoInfoPage(userId: string) {
    navigation.navigate("UserDetail", {
      userId,
    });
  }

  // 跳转到详情页面
  function gotoDetail(id: string) {
    navigation.navigate("DeynamicDetails", { id });
  }

  return (
    <SafeAreaView style={styles.container}>
      {/* 顶部布局 */}
      <View style={styles.tabbar}>
        <ScrollView horizontal={true}>
          <View style={styles.tabbarScroll}>
            <Text style={styles.tabbarText}>关注</Text>
            <Pressable
              onPress={() => {
                getArticleList();
              }}
            >
              <Text style={[styles.tabbarText, styles.tabbarTextActive]}>
                推荐
              </Text>
            </Pressable>
          </View>
        </ScrollView>
        <Icon
          name="search"
          style={styles.tabbarSearch}
          size={20}
          color="#666"
        ></Icon>
      </View>
      <ScrollView
        horizontal={true}
        showsHorizontalScrollIndicator={false}
        decelerationRate="fast"
        snapToInterval={width}
      >
        <ScrollView style={styles.scrollView}>
          <View style={styles.scrollViewHome}>
            {articleList?.map((item) => (
              <View style={styles.homeItem} key={item.article_id}>
                <View style={styles.info}>
                  <Pressable
                    style={styles.infoLeft}
                    onPress={() => {
                      gotoInfoPage(item.author.id);
                    }}
                  >
                    <View style={styles.infoCover}>
                      <Image
                        style={styles.infoCoverImage}
                        source={{
                          uri: BASE_URL + item.author.avatar,
                        }}
                      />
                    </View>
                    <View style={styles.infoMiddle}>
                      <Text style={styles.infoName}>{item.author.name}</Text>
                      <Text style={styles.infnTime}>
                        {friendlyTimeAgo(new Date(item.createdAt))}
                      </Text>
                    </View>
                  </Pressable>
                  <View style={styles.infoFocus}>
                    <Text style={styles.infoFocusText}>关注</Text>
                  </View>
                </View>
                <Pressable
                  onPress={() => {
                    gotoDetail(item.article_id);
                  }}
                  style={styles.dynamic}
                >
                  <Text style={styles.dynamicTitle}>{item.title}</Text>
                  <Text style={styles.dynamicContent} numberOfLines={3}>
                    {item.content}
                  </Text>
                  <View style={styles.dynamicCovers}>
                    {item?.covers?.map(
                      (cover: any, index) =>
                        index < 3 && (
                          <View key={cover.id} style={styles.dynamicCover}>
                            {/* <Text>{cover}</Text> */}
                            <Image
                              style={[styles.dynamicCoverImage]}
                              source={{
                                uri: BASE_URL + cover.url,
                              }}
                            />
                          </View>
                        )
                    )}
                    {item.covers.length > 3 && (
                      <View style={styles.dynamicCoversNum}>
                        <Text style={styles.dynamicCoversNumText}>
                          +{item.covers.length - 3}
                        </Text>
                      </View>
                    )}
                  </View>
                  <View style={styles.dynamicFooter}>
                    <View style={styles.dynamicFooterLeft}>
                      <View style={styles.dynamicFooterItem}>
                        <Icon
                          style={styles.dynamicFooterItemIcon}
                          name="boat-outline"
                          size={20}
                          color="#666"
                        />
                        <Text style={styles.dynamicFooterItemText}>{
                          item.likeCount
                        }</Text>
                      </View>
                      <View style={styles.dynamicFooterItem}>
                        <Icon
                          style={styles.dynamicFooterItemIcon}
                          name="chatbubble-ellipses-outline"
                          size={20}
                          color="#666"
                        />
                        <Text style={styles.dynamicFooterItemText}>
                          {item.commentCount}
                        </Text>
                      </View>
                    </View>
                    <View style={styles.dynamicFooterRight}>
                      <Icon
                        style={styles.dynamicFooterRightIcon}
                        name="ellipsis-horizontal"
                      />
                    </View>
                  </View>
                </Pressable>
              </View>
            ))}
          </View>
        </ScrollView>
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  tabbar: {
    // backgroundColor: "#eee",
    flexDirection: "row",
    alignItems: "center",
    // padding: 10,
    paddingHorizontal: 10,
    paddingVertical: 4,
  },
  tabbarScroll: {
    // justifyContent: "flex-start",
    flexDirection: "row",
    alignItems: "flex-end",
  },
  tabbarText: {
    fontSize: 16,
    margin: 6,
    // marginLeft:10,
    color: "#333",
  },
  tabbarTextActive: {
    fontSize: 20,
    color: "#12b886",
    fontWeight: "bold",
  },
  tabbarSearch: {
    paddingLeft: 14,
  },
  scrollView: {
    flex: 1,
    width: width,
    // height: height,
    // backgroundColor: "pink",
  },
  scrollViewHome: {
    width: width,
    backgroundColor: "#fff",
  },
  homeItem: {
    padding: 10,
  },
  info: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    paddingBottom: 10,
  },
  infoLeft: {
    flexDirection: "row",
    alignItems: "center",
  },
  infoCover: {
    width: 40,
    height: 40,
    borderRadius: 22,
    marginRight: 10,
    overflow: "hidden",
  },
  infoCoverImage: {
    width: "100%",
    height: "100%",
  },
  infoMiddle: {
    height: 40,
    justifyContent: "space-around",
    // flex: 1,
  },
  infoName: {
    fontSize: 16,
    // fontWeight: "bold",
  },
  infnTime: {
    fontSize: 12,
    color: "#999",
  },
  infoFocus: {
    // backgroundColor: "#12b886",
    backgroundColor: "#e6fcf5",
    paddingHorizontal: 20,
    paddingVertical: 6,
    borderRadius: 20,
  },
  infoFocusText: {
    fontSize: 12,
    color: "#12b886",
  },
  dynamic: {
    // backgroundColor:'red'
  },
  dynamicTitle: {
    fontSize: 16,
    fontWeight: "bold",
    // marginBottom: 4,
  },
  dynamicContent: {
    fontSize: 16,
    lineHeight: 24,
  },
  dynamicCovers: {
    flexDirection: "row",
    // justifyContent: "space-between",
    marginVertical: 10,
  },
  dynamicCover: {
    flexBasis: "32.5%",
    borderRadius: 10,
    overflow: "hidden",
    marginRight: "1.2%",
  },
  dynamicCoverImage: {
    flexBasis: "33%",
    width: "100%",
    aspectRatio: 1,
  },
  dynamicCoversNum: {
    position: "absolute",
    right: 0,
    bottom: 0,
    paddingHorizontal: 5,
    paddingVertical: 2,
    backgroundColor: "rgba(0,0,0,0.5)",
    borderTopLeftRadius: 10,
    borderBottomRightRadius: 10,
    overflow: "hidden",
    color: "#fff",
    width: 30,
    height: 30,
    alignItems: "center",
    justifyContent: "center",
  },
  dynamicCoversNumText: {
    color: "#fff",
    fontSize: 10,
  },
  dynamicFooter: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    paddingBottom: 20,
    borderBottomWidth: 1,
    borderBottomColor: "#f8f8f8",
  },
  dynamicFooterLeft: {
    flexDirection: "row",
  },
  dynamicFooterItem: {
    flexDirection: "row",
    alignItems: "center",
    marginRight: 20,
  },
  dynamicFooterItemIcon: {
    fontSize: 20,
    color: "#333",
  },
  dynamicFooterItemText: {
    fontSize: 14,
    marginLeft: 5,
    color: "#555",
  },
  dynamicFooterRight: {},
  dynamicFooterRightIcon: {
    color: "#999",
    fontSize: 20,
  },
});
